# -*- coding: utf-8 -*-
# @Time    : 2018/2/5 13:11
# @Author  : Soft
# @File    : controller.py
# @Desc    : 后台管理界面控制器
import random
import string

from module.admin import admin, ad_login
from flask import render_template, request, jsonify, session, make_response
from module.admin.service import AdminService, Admin
from module.class_.service import ClzService
from module.user.service import StuService
from module.cache import cache

a_db = AdminService()


def random_str(ln=5):
    return ''.join(random.sample(string.ascii_letters + string.digits, ln))


def is_same_str(s1='', s2=''):
    try:
        return s1.lower() == s2.lower()
    except BaseException as e:
        return False


@ad_login.loader
def get_a(aid):
    return AdminService.get_name_pass(aid)


@admin.route('/')
@ad_login.required
def a_admin():
    now_class = ClzService.get_now_clazz()
    # 这里要进行设置，设置为2020年注册的学生才能正常显示
    stu_total_num = StuService.stu_count(2020)
    return render_template('admin/admin.html', name=ad_login.get_user_name(),
                           stu_total_num=stu_total_num,
                           now_class=now_class,
                           reg_lock=cache.get('reg_lock'),
                           work_lock=cache.get('work_lock'))


@admin.route('/login', methods=['get', 'post'])
def a_login():
    if request.method == 'GET':
        key = random_str(12)
        code = random_str(4)
        cache.set(key, code)
        return render_template('admin/login.html', key=key, code=code)
    elif request.method == 'POST':
        username = request.form.get('username', 'o')
        password = request.form.get('password', 'o')
        remember = request.form.get('remember', 0)
        code = request.form.get('code', '')
        key = request.form.get('key', '')
        right_code = cache.get(key)
        if not is_same_str(code, right_code):
            return jsonify(status=False, reason='验证码错误')

        result = a_db.login(username, password, True)
        if result[0]:
            res = make_response(jsonify(status=True))
            if remember == 'true':
                ad_login.login(res, result[1].id, result[1].ad_name, result[1].ad_pass, remember=True)
            else:
                ad_login.login(res, result[1].id, result[1].ad_name, result[1].ad_pass)
            return res
        return jsonify(status=False, reason='账号密码错误')


@admin.route('/logout', methods=['post'])
@ad_login.required
def a_logout():
    res = make_response(jsonify(status=True))
    return ad_login.logout(response=res)


@admin.route('/list')
@ad_login.required
def admin_list():
    page = int(request.args.get('page', 1))
    return render_template('admin/a_list.html', name=ad_login.get_user_name(), a_page=a_db.pages(page))


@admin.route('/add', methods=['get', 'post'])
@ad_login.required
def add():
    if request.method == 'GET':
        return render_template('admin/add.html', name=ad_login.get_user_name())
    elif request.method == 'POST':
        na = request.form.to_dict()
        name = na.get('ad_name')
        if a_db.query_name(name=name):
            return jsonify(status=False, msg='用户已存在')
        if a_db.add(**na):
            return jsonify(status=True)
        return jsonify(status=False, msg='内部错误')


@admin.route('/delete', methods=['post'])
@ad_login.required
def delete():
    aid = request.form.get('id')
    name = a_db.query_sql('select ad_name from admin where id = %s', aid)[0].get('ad_name')
    if name == 'admin':
        return jsonify(status=False, msg='超级管理员禁止删除')
    if a_db.remove(aid=aid):
        return jsonify(status=True)
    return jsonify(status=False)


@admin.route('/change', methods=['get', 'post'])
@ad_login.required
def change():
    if request.method == 'GET':
        return render_template('/admin/change.html', name=ad_login.get_user_name(),
                               admin=a_db.get_by_id(int(ad_login.get_user_id())))
    elif request.method == 'POST':
        forms = request.form.to_dict()
        for k, v in forms.items():
            if len(v) <= 0:
                forms.pop(k)
        old_name = forms.pop('old_name')
        if len(forms) > 0:
            if a_db.change(old_name, **forms):
                return jsonify(status=True, msg='修改成功')
        return jsonify(status=False, msg='无信息修改')


@admin.route('/search', methods=['post'])
@ad_login.required
def search():
    name = request.form.get('username').strip()
    result = a_db.query_name(name=name)
    if len(result):
        return jsonify(result=result, status=True)
    return jsonify(result=None, status=False)
